﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.UI;
using System.Web.UI.WebControls;
using Giaiphongmatbang.DataModel;
using Giaiphongmatbang.BLL;
using System.Text;

namespace Giaiphongmatbang
{
    public partial class Hotronghenghiep : System.Web.UI.Page
    {
        private bool IsPageRefresh = false;
        User user;

        protected void Page_Load(object sender, EventArgs e)
        {
            user = (User)Session["User"];
            if (user == null)
            {
                ibtnAdd.Visible = false;
            }

            if (!IsPostBack)
            {
                if (Session["User"] != null)
                {
                    if (!new UserRolesRepository().CheckRoles(user, (int)Utility.Enum.Roles.ManagerPrices))
                    {
                        ibtnAdd.Visible = false;
                    }
                }
                list.Clear();
                list = getParent();
                BindData();
                binDropdownList(ddlParent);
                ddlParent.DataBind();
            }
            if (Page.IsPostBack)
            {
                if (ViewState["postid"] != null && Session["postid"] != null && (string)ViewState["postid"] != (string)Session["postid"].ToString())
                    IsPageRefresh = true;
            }
            Session["postid"] = System.Guid.NewGuid().ToString();
            ViewState["postid"] = Session["postid"];
        }

        QLGPMBEntities db = new QLGPMBEntities();
        static List<SupportJob> list = new List<SupportJob>();
        static int n;

        List<SupportJob> getParent()
        {
            return db.SupportJobs.Where(p => p.ParentID == 0).ToList();
        }

        List<SupportJob> getChild(int ParentID)
        {
            return db.SupportJobs.Where(p => p.ParentID == ParentID).ToList();
        }

        List<SupportJob> getChildList(int ParentID)
        {
            return list.Where(p => p.ParentID == ParentID).ToList();
        }
        string img(int id)
        {
            if (!db.SupportJobs.Any(p => p.ParentID == id))
                return "&nbsp;&nbsp;&nbsp;&nbsp;";
            if (!list.Any(p => p.ParentID == id))
                return "<a href='javascript:expand(" + id + ");'><img src='/Images/plus.gif'/></a>";
            return "<a href='javascript:collapse(" + id + ");'><img src='/Images/minus.gif'/></a>";
        }
        protected void BindData()
        {
            n = 1;
            StringBuilder str = new StringBuilder("<table class='treetable' width='100%'>");
            str.Append("<tr><th style=\"width:25px\">TT</th><th>Hình thức hỗ trợ</th><th style=\"width:100px\">Mức hỗ trợ</th><th style=\"width:90px\">Thao tác</th></tr>");
            foreach (var item in list.Where(p => p.ParentID == 0))
            {
                StringBuilder node = new StringBuilder("<tr><td style=\"text-align: center;\">" + n + "</td>");
                node.Append("<td>" + img(item.SuportJobID) + item.SupportName + "</td>");
                node.Append("<td style=\"text-align: center;\">" + (item.UnitPrice.HasValue ? ((int)item.UnitPrice).ToString("###,###") : null) + "</td>");
                if (user != null && new UserRolesRepository().CheckRoles(user, (int)Utility.Enum.Roles.ManagerPrices))
                {
                    node.Append("<td style=\"text-align: center;\"><a Onclick=\"return addjob(" + item.SuportJobID + ")\">");
                    node.Append("<img src='/Images/folder_add.png'/ title=\"Thêm mới\"></a>");
                    node.Append("&nbsp;&nbsp;<a onclick=\"return editjob(" + item.SuportJobID + ",'" + item.SupportName + "','" + item.UnitPrice + "'," + item.ParentID + ",'" + item.Description + "')\">");
                    node.Append("<img src='/Images/pen.png'/ title=\"Sửa\"></a>");
                    if (getChild(item.SuportJobID).Count == 0)
                    {
                        node.Append("&nbsp;&nbsp;<a onclick=\"return deletejob(" + item.SuportJobID + ")\"><img src='/Images/delete.png'title=\"Xóa\"/></a></td>");
                    }
                }
                else
                {
                    node.Append("<td></td>");
                }
                node.Append("</tr>");
                n++;
                BindDataChild(node, item.SuportJobID, "", ref n);
                str.AppendLine(node.ToString());
            }
            str.AppendLine("</table>");
            ltr.Text = str.ToString();

        }
        protected void BindDataChild(StringBuilder parent, int ParentID, string indent,ref int tt)
        {
            var list = getChildList(ParentID);
            indent += "&nbsp&nbsp&nbsp&nbsp&nbsp&nbsp&nbsp";
            foreach (var item in list)
            {
                StringBuilder node = new StringBuilder("<tr><td style=\"text-align: center;\">" + tt + "</td>");
                node.Append("<td>" + indent + img(item.SuportJobID) + item.SupportName + "</td>");
                node.Append("<td style=\"text-align: center;\">" + (item.UnitPrice.HasValue ? ((int)item.UnitPrice).ToString("###,###") : null) + "</td>");
                if (user != null && new UserRolesRepository().CheckRoles(user, (int)Utility.Enum.Roles.ManagerPrices))
                {
                    node.Append("<td style=\"text-align: center;\"><a Onclick=\"return addjob(" + item.SuportJobID + ")\">");
                    node.Append("<img src='/Images/folder_add.png' title=\"Thêm mới\"/></a>");
                    node.Append("&nbsp;&nbsp;<a onclick=\"return editjob(" + item.SuportJobID + ",'" + item.SupportName + "','" + item.UnitPrice + "'," + item.ParentID + ",'" + item.Description + "')\">");
                    node.Append("<img src='/Images/pen.png'/ title=\"Sửa\" /></a>");
                    if (getChild(item.SuportJobID).Count == 0)
                    {
                        node.Append("&nbsp;&nbsp;<a onclick=\"return deletejob(" + item.SuportJobID + ")\"><img src='/Images/delete.png'title=\"Xóa\"/></a></td>");
                    }
                }
                else
                {
                    node.Append("<td></td>");
                }
                node.Append("</tr>");
                tt++;
                BindDataChild(node, item.SuportJobID, indent,ref tt);
                parent.AppendLine(node.ToString());

            }
            n = tt;
        }

        public void Expand(int ID)
        {
            var dataExpand = getChild(ID);
            foreach (var item in dataExpand)
            {
                list.Add(item);
            }
        }

        public void Collapse(int ID)
        {
            var dataCollapse = getChild(ID);
            list.RemoveAll(p => p.ParentID == ID);
        }

        protected void btnExpand_Click(object sender, EventArgs e)
        {
            int ID = int.Parse(hdf.Value);
            if (IsPageRefresh)
            {
                Expand(ID);
            }
            BindData();
        }

        protected void btnCollapse_Click(object sender, EventArgs e)
        {
            int ID = int.Parse(hdf.Value);
            Collapse(ID);
            BindData();
        }

        SupportJobRepository objjob = new SupportJobRepository();

        protected void btnDelete_Click(object sender, EventArgs e)
        {
            int ID = int.Parse(hdf.Value);
            objjob.DeleteByID(ID);
            objjob.Save();
            list.RemoveAll(p => p.SuportJobID == ID);
            BindData();
            binDropdownList(ddlParent);
            ddlParent.DataBind();
        }

        protected void btnAddJob_Click(object sender, EventArgs e)
        {
            if (!IsPageRefresh)
            {
                Boolean modenew = Boolean.Parse(hdfmodenew.Value);
                SupportJob job = new SupportJob();
                if (txtSupportName.Text.Trim().Equals(""))
                {
                    return;
                }
                if (modenew)
                {
                    job.SupportName = txtSupportName.Text.Trim();
                    try
                    {
                        if (txtUnitPrice.Text.Trim() != "")
                        {
                            job.UnitPrice = decimal.Parse(txtUnitPrice.Text.Trim());
                        }
                        job.ParentID = int.Parse(ddlParent.SelectedValue);
                    }
                    catch
                    {
                    }
                    job.Description = txtDescriptions.Text.Trim();
                    job.CreatedBy = user.UserName;
                    job.CreatedDate = DateTime.Now.Date;
                    objjob.Insert(job);
                    objjob.Save();
                    list.Add(job);
                }
                else
                {
                    job = objjob.GetByID(int.Parse(hdf.Value));
                    job.SupportName = txtSupportName.Text.Trim();

                    try
                    {
                        if (txtUnitPrice.Text.Trim() != "")
                        {
                            job.UnitPrice = decimal.Parse(txtUnitPrice.Text.Trim());
                        }
                        if (!job.SuportJobID.ToString().Equals(ddlParent.SelectedValue))
                        {
                            job.ParentID = int.Parse(ddlParent.SelectedValue);
                        }
                    }
                    catch
                    {
                    }
                    job.Description = txtDescriptions.Text.Trim();
                    job.ModifiedBy = user.UserName;
                    job.ModifiedDate = DateTime.Now.Date;
                    objjob.Save();
                    int index = list.FindIndex(p => p.SuportJobID == job.SuportJobID);
                    list.RemoveAt(index);
                    list.Insert(index, job);
                }
            }
            binDropdownList(ddlParent);
            ddlParent.DataBind();
            BindData();
        }


        public List<SupportJob> getall()
        {
            return db.SupportJobs.ToList();
        }
        public void binDropdownList(DropDownList ddl)
        {
            ddl.Items.Clear();

            List<SupportJob> list = getall();
            foreach (var item in list)
            {
                if (item.ParentID == 0)
                {
                    ListItem i = new ListItem();
                    i.Text = item.SupportName;
                    i.Value = item.SuportJobID.ToString();
                    ddl.Items.Add(i);
                    getchildItem(item.SuportJobID, list, ddl, "");
                }
            }

            ListItem topitem = new ListItem();
            topitem.Value = "0";
            topitem.Text = "--Chọn hỗ trợ chuyển đổi nghề nghiệp--";
            ddl.Items.Insert(0, topitem);
        }

        public void getchildItem(int parentID, List<SupportJob> list, DropDownList ddl, string indent)
        {
            indent += "---";
            foreach (var item in list)
            {

                if (item.ParentID == parentID)
                {
                    ListItem i = new ListItem();
                    i.Value = item.SuportJobID.ToString();
                    i.Text = indent + item.SupportName;
                    ddl.Items.Add(i);
                    getchildItem(item.SuportJobID, list, ddl, indent);
                }
            }
        }   
    }
}